<template>
  <div class="seat-map">
    <h1>图书馆座位预约</h1>
    <div class="seat-grid">
      <div
        v-for="(seat, index) in seats"
        :key="index"
        class="seat"
        :class="{ 'seat-available': !seat.booked, 'seat-booked': seat.booked }"
        @click="toggleSeat(index)"
      >
        {{ seat.number }}
        <div v-if="seat.booked" class="seat-status">已预约</div>
      </div>
    </div>
    <button @click="submitReservation" :disabled="!hasSelectedSeats">提交预约</button>
  </div>
</template>

<script>
export default {
  data() {
    return {
      seats: Array.from({ length: 20 }, (_, i) => ({
        number: i + 1,
        booked: false,
      })),
      selectedSeats: [],
    };
  },
  computed: {
    hasSelectedSeats() {
      return this.selectedSeats.length > 0;
    },
  },
  methods: {
    toggleSeat(index) {
      const seat = this.seats[index];
      if (seat.booked) {
        this.deselectSeat(index);
      } else {
        this.selectSeat(index);
      }
    },
    selectSeat(index) {
      this.selectedSeats.push(index);
      this.seats[index].booked = true;
    },
    deselectSeat(index) {
      const indexToRemove = this.selectedSeats.indexOf(index);
      if (indexToRemove !== -1) {
        this.selectedSeats.splice(indexToRemove, 1);
        this.seats[index].booked = false;
      }
    },
    submitReservation() {
      console.log('预约的座位:', this.selectedSeats.map(index => this.seats[index].number));
      alert('预约已提交！');
      this.selectedSeats = [];
      this.seats = this.seats.map(seat => ({ ...seat, booked: false }));
    },
  },
};
</script>

<style scoped>
.seat-map {
  text-align: center;
}
.seat-grid {
  display: grid;
  grid-template-columns: repeat(4, 1fr);
  gap: 10px;
  margin: 20px auto;
  max-width: 600px;
}
.seat {
  width: 100px;
  height: 100px;
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  border: 1px solid #ccc;
  cursor: pointer;
  user-select: none;
}
.seat-number {
  font-size: 1.2em;
  font-weight: bold;
}
.seat-status {
  color: red;
  font-size: 0.8em;
}
.seat-available {
  background-color: #e0f7fa;
}
.seat-booked {
  background-color: #f8d7da;
}
</style>